package cn.cumulomq.db;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.log4j.Logger;

import cn.cumulomq.dao.TeleMessageDao;
import cn.cumulomq.entity.Address;
import cn.cumulomq.service.AftnChannelService;
import cn.cumulomq.utils.FileUtil;
import cn.cumulomq.utils.PropertiesUtil;

public class MessageDB {
	private static Logger logger = Logger.getLogger(AftnChannelService.class);
	private static Map<String,SqlSessionFactory> sqlSessionFactoryMap = new HashMap<String,SqlSessionFactory>();
	public static final String TEMPLATE_MESSAGE_DB_NAME="message.db";
	public static SqlSessionFactory getSessionFactory(String addr){
		SqlSessionFactory ssf = sqlSessionFactoryMap.get(addr);
		if(ssf==null){
			createDatabase(addr);
			logger.info("Create SqlSessionFactory,database : "+getDBName(addr));
			Properties properties = new Properties();
			properties.setProperty("driver","org.sqlite.JDBC");
			properties.setProperty("url", "jdbc:sqlite:"+PropertiesUtil.getProperty("messagedb.path")+getDBName(addr));
			properties.setProperty("username", "");
			properties.setProperty("password", "");
			logger.info(properties.toString());
			PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
			pooledDataSourceFactory.setProperties(properties);
			DataSource dataSource = pooledDataSourceFactory.getDataSource();
			TransactionFactory transactionFactory = new JdbcTransactionFactory();
			Environment environment = new Environment("development", transactionFactory, dataSource);
			Configuration configuration = new Configuration(environment);
			configuration.addMapper(TeleMessageDao.class);
			ssf = new SqlSessionFactoryBuilder().build(configuration);
			sqlSessionFactoryMap.put(addr, ssf);
		}
		return ssf;
	}
	public static String getDBName(String address){
		return address+".db";
	}
	private static void createDatabase(String address){
		String messageDBPath = PropertiesUtil.getProperty("messagedb.path")+MessageDB.getDBName(address);
		File messageDBFile = new File(messageDBPath);
		if(messageDBFile.exists())logger.info("Message["+address+"] datebase is exists."+messageDBFile.getAbsolutePath());
		if(!messageDBFile.getParentFile().exists()){
			messageDBFile.getParentFile().mkdirs();
			InputStream inputStream = null;
			try {
				inputStream = Resources.getResourceAsStream(MessageDB.TEMPLATE_MESSAGE_DB_NAME);
				FileUtil.inputStreamToFile(inputStream, messageDBFile);
				logger.info("Create new message["+address+"] datebase success."+messageDBFile.getAbsolutePath());
			} catch (IOException e) {
				logger.error("Create message["+address+"] database error."+messageDBFile.getAbsolutePath(),e);
			}
		}
	}
}
